--[[-------------------------------------------------------------------------
  Copyright (c) 2007, Kyahx
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:

      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above
        copyright notice, this list of conditions and the following
        disclaimer in the documentation and/or other materials provided
        with the distribution.
      * Neither the name of this AddOn nor the names of its contributors
        may be used to endorse or promote products derived from this
        software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------]]

local L = setmetatable({}, {
    __index=function(t,k) return k end,
    __call=function(t,k) return k end,
})

--[[-------------------------------------------------------------------------
    Magic
---------------------------------------------------------------------------]]
local _G = getfenv(0)

local function safeloadstring(k)
    local vs = { strsplit(".", k) }
    local v = ''
    local s = getn(vs)
    
    for i=1, s do
        if i == s then break end
        v = v .. vs[i]
        if not loadstring("return " .. v)() then return end
        v = v .. '.'
    end
    
    return loadstring("return " .. k)()
end

local _F = setmetatable({}, {
    __index = function(t,k)
        local frame = _G[k] or safeloadstring(k)
        frame = frame and type(frame.GetName) == 'function' and frame
        
        if not frame then return end
        
        rawset(t,k,frame)
        return frame
    end,
})

local DASHSTRATA = "DIALOG"

--[[-------------------------------------------------------------------------
    Mazzlegasm!
---------------------------------------------------------------------------]]
Dash = CreateFrame("Frame", "Dashboard", UIParent)

BINDING_HEADER_DASHBOARD_HEADER = L"Dash"
BINDING_NAME_DASHBOARD_TOGGLE = L"Toggle Dash"

function Dash:PortOldSV()
    if self.db.profile and not self.db.profile.frames then
        self:Print("Old Saved Data found")
        for k,v in pairs(self.db.profile) do
            self:Print("Porting: " .. k)
            self.db.profile.frames = self.db.profile.frames or {}
            self.db.profile.frames[k] = v
            self.db.profile[k] = nil
        end
    end
end

function Dash:Initialize()
    self.db = self:InitializeDB("DashDB", {
        hotspot = "TOPRIGHT",
        frames = {},
    })
    
    self:PortOldSV()
    
    -- Dongle's DB dosent seem to like empty tables in defaults
    self.db.profile.frames = self.db.profile.frames or {}
    
    self.frames = self.db.profile.frames
    self:RegisterSlashCommands()
end

function Dash:Enable()
    self:Hide()

    self:SetBackdrop({
        bgFile = "Interface\\ChatFrame\\ChatFrameBackground", tile = true, tileSize = 16,
        insets = {left = 0, right = 0, top = 0, bottom = 0},
    })
    self:SetBackdropColor(0,0,0,0.5)

    self:ClearAllPoints()
    self:SetAllPoints(UIParent)

    self:SetFrameStrata(DASHSTRATA)
    self:SetFrameLevel(0)
    
    self:AddHotspot(self.db.profile.hotspot or "TOPRIGHT")
    
    self:StealAll()
    self:RegisterEvent("MEETINGSTONE_CHANGED", "StealAll") -- Catch some frames after PEW
end

function Dash:Toggle()
    self:StealAll()
    if self:IsShown() then
        self:FadeOut()
    else
        self:FadeIn()
    end
end

function Dash:FadeOut()
    UIFrameFadeOut(self, .15, 1, 0)
    self.fadeInfo.finishedFunc = function() self:Hide() end
end

function Dash:FadeIn()
    self:Show()
    UIFrameFadeIn(self, .15, 0, 1)
end

function Dash:AddHotspot(corner)
    local spot = CreateFrame("Frame", nil, UIParent)
    spot:SetWidth(2)
    spot:SetHeight(2)
    spot:SetFrameStrata("TOOLTIP")
    spot:SetPoint(corner, UIParent)
    spot:EnableMouse(true)
    spot:SetScript("OnEnter", function() Dash:Toggle() end)
end

--[[-------------------------------------------------------------------------
    You no take Candle!
---------------------------------------------------------------------------]]

local blacklist = {
	Dashboard = true,
	UIParent = true,
	WorldFrame = true,
}

local tmp_frame, tmp_string
StaticPopupDialogs["DASHBOARD_PROTECTED"] = {
    showAlert = 1,
    text = "This frame is protected and may taint the dashboard.\nAdd anyway?",
    button1 = "Yes",
    button2 = "No",
    OnAccept = function()
        Dash:Steal(tmp_frame, tmp_string, true)
        tmp_frame, tmp_string = nil, nil
    end,
    OnCancel = function()
        Dash.frames[tmp_string] = nil
    end,
    timeout = 0,
    whileDead = 1,
    hideOnEscape = 1,
}

function Dash:StealAll()
    local frame
    for name,force in pairs(self.frames) do
        frame = _F[name]
        if frame then
            self:Steal(frame, nil, force)
        end
    end
end

function Dash:Steal(frame, string, force)
    if blacklist[frame:GetName()] then
        return self:Print("Blacklisted frame: " .. frame:GetName())
    end

    if not force and frame:IsProtected() then
        tmp_frame, tmp_string = frame, string
        StaticPopup_Show("DASHBOARD_PROTECTED")
        return
    end
    
    if string then
        self:Print("Added: " .. string)
        self.frames[string] = true
    end
    
    frame:SetParent(self)
    frame:SetFrameStrata(DASHSTRATA)
end

--[[-------------------------------------------------------------------------
    Slashy Slashy
---------------------------------------------------------------------------]]

function Dash:Add(string)
    local frame = _F[string]
    if frame then
        self:Steal(frame, string)
    end
end

function Dash:Addmouse()
    local frame = GetMouseFocus()
    
    if frame then
        if not type(frame.GetName) == 'function' or not frame:GetName() then
            self:Print("This frame has no global name, and cannot be added via the mouse")
        else
            self:Steal(frame, frame:GetName())
        end
    end
end

function Dash:Remove(string)
    local frame = _F[string]
    if frame then
        frame:SetParent(UIParent)
        frame:SetFrameStrata("MEDIUM")
    end
    self.frames[string] = nil
end

function Dash:List()
    local s = "Managed Frames:"
    for name,_ in pairs(self.frames) do
        s = s .. "\n    " .. name
    end
    if s == "Managed Frames:" then s = "Managed Frames:\n    None" end
    self:Print(s)
end

function Dash:Listmouse()
    local frame = GetMouseFocus()
    if frame then
        if type(frame.GetName) == 'function' then
            self:Print("Frame under mouse cursor: " .. (frame:GetName() or tostring(frame)) )
        else
            self:Print("Not a frame.")
        end
    end
end

function Dash:Clear()
    self.db:ResetProfile()
    self:Print("Cleared DB")
end

local cmdList = {
    {
        name = L"add",
        desc = L"Add a frame to the dash.",
        pattern = L"^add (.+)",
        handler = "Add",
    },
    {
        name = L"addmouse",
        desc = L"Add the frame underneath the mouse cursor to the dash.",
        pattern = L"^addmouse$",
        handler = "Addmouse",
    },
    {
        name = L"remove",
        desc = L"Remove a frame from the dash.",
        pattern = L"^remove (.+)",
        handler = "Remove",
    },
    {
        name = L"list",
        desc = L"List the frames on the dash.",
        pattern = L"^list$",
        handler = "List",
    },
    {
        name = L"listmouse",
        desc = L"List the frame under the mouse cursor.",
        pattern = L"^listmouse$",
        handler = "Listmouse",
    },
    {
        name = L"clear",
        desc = L"Clear the dash.",
        pattern = L"^clear$",
        handler = "Clear",
    },
}

function Dash:RegisterSlashCommands()
    local cmdStr = "|cFF33FF99%s|r: %s"
    local slash = self:InitializeSlashCommand(L"|cFF33FF99Dash Slash Command|r", "DASH", L"dash")
    for i,c in ipairs(cmdList) do
        slash:RegisterSlashHandler(format(cmdStr, c.name, c.desc), c.pattern, c.handler)
    end
    self.slash = slash
end

--[[-------------------------------------------------------------------------
    It's Alive
---------------------------------------------------------------------------]]
Dash = DongleStub("Dongle-1.0"):New("Dash", Dash)

